package com.bowen.demo.demo001.sharedata.method2;

/**
 * <h3>java-study</h3>
 * <p>多线程共享数据实现</p>
 * @author : zhang.bw
 * @date : 2021-04-28 14:18
 **/
public class MyData {

	private int j=0;
	public  synchronized void add(){
		System.out.println("addj的当前值为："+Thread.currentThread().getName()+"="+getData());
		j++;
		System.out.println("ADD线程"+Thread.currentThread().getName()+"j 为："+j);
	}
	public  synchronized void dec(){
		System.out.println("decj的当前值为："+Thread.currentThread().getName()+"="+getData());
		j--;
		System.out.println("DEC线程"+Thread.currentThread().getName()+"j 为："+j);
	}
	public int getData(){
		return j;
	}

}

class TestThread {

	public static void main(String[] args) {
		final MyData data = new MyData();
		for(int i=0;i<2;i++){
			new Thread(new Runnable(){
				@Override
				public void run() {
				data.add();
				}
			}).start();

			new Thread(new Runnable(){
				@Override
				public void run() {
				data.dec();
				}
			}).start();
		}
	}
}
